package com.example.netty.tcp;

import com.example.netty.tcp.codec.JsonDecoder;
import com.example.netty.tcp.codec.JsonEncoder;
import com.example.netty.tcp.codec.JsonDecoder;
import com.example.netty.tcp.codec.JsonEncoder;
import com.example.netty.tcp.handler.DeviceHandler;
import com.example.netty.tcp.message.ControlRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;import com.example.netty.tcp.handler.DeviceHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

public class DeviceClient {
    private static final String HOST = "127.0.0.1";
    private static final int PORT = 8080;
    private static final Logger logger = LoggerFactory.getLogger(DeviceHandler.class);

    private final EventLoopGroup workerGroup = new NioEventLoopGroup();
    private Channel channel;
    private String deviceId;

    public DeviceClient(String deviceId) {
        this.deviceId = deviceId;
    }

    public void start() throws Exception {
        Bootstrap b = new Bootstrap();
        b.group(workerGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(
                                new IdleStateHandler(0, 0, 30, TimeUnit.SECONDS),
                                new JsonDecoder(),       // 仅保留JSON解码器
                                new JsonEncoder(),       // 仅保留JSON编码器
                                new DeviceHandler(DeviceClient.this)
                        );
                    }
                });

        channel = b.connect(HOST, PORT).sync().channel();
        System.out.println("设备[" + deviceId + "]已连接到服务器: " + HOST + ":" + PORT);
        channel.closeFuture().sync();
    }
    public void sendControlCommand(String signalId, String value) {
        ControlRequest request = new ControlRequest();
        request.setDevId(deviceId);
        request.setTxnNo(System.currentTimeMillis()); // 13位时间戳
        request.addControlParam(signalId, value); // 添加信号量ID和控制值
        sendMessage(request);
        logger.info("发送远程控制指令：信号量ID={}, 值={}", signalId, value);
    }
    public void sendMessage(Object message) {
        if (channel != null && channel.isActive()) {
            channel.writeAndFlush(message);
        } else {
            System.err.println("无法发送消息: 连接未激活");
        }
    }

    public void stop() {
        if (channel != null) {
            channel.close();
        }
        workerGroup.shutdownGracefully();
    }

    public String getDeviceId() {
        return deviceId;
    }

    public static void main(String[] args) {
        String deviceId = "BT1048030120HC2042626007";//假设设备是这么个id
        try {
            DeviceClient client = new DeviceClient(deviceId);
            client.start();
        } catch (Exception e) {
            System.err.println("客户端启动失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
